package global_village.data.utils;

import global_village.app.Utils;
import global_village.data.ServerRequest;
import global_village.gui.utils.StatusListener;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class AsyncHttpQuery extends AsyncTask<ServerRequest, Void, String> {

	private static final String TAG = AsyncHttpQuery.class.getSimpleName();
	
	private ServerRequest sr;
	private StatusListener st;
	
	public void setOnStatusListener(StatusListener st){
		this.st = st;
	}
	
	@Override
	protected void onPreExecute() {
		Log.i(TAG, "< onPreExecute >");
		super.onPreExecute();
		
		if(!Utils.isInternetConnected()){
			Utils.showToast("There is no internet connection");
			this.cancel(true);
		}
		if(st!=null)
			st.showStatus("Downloading Data...");
	}
	
	@Override
	protected String doInBackground(ServerRequest... params) {
		Log.i(TAG, "< doInBackground >");
		
		sr = params[0];
		String data = null;
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = null;
		
		try {
			response = getResponseForRequest(httpClient);
		} catch (Exception e){
			Log.e(TAG, e.toString());
			this.cancel(true);
		}
		
		int statusCode = response.getStatusLine().getStatusCode();
		
		switch(statusCode){
		case 200: //OK
		case 201: //CREATED
			Log.v(TAG, "http code " + statusCode + " - request succeeded");
			HttpEntity entity = response.getEntity();
			
			try { 
				data = EntityUtils.toString(entity);
			} catch (ParseException e) {
				Log.e(TAG, e.toString());
			} catch (IOException e) {
				Log.e(TAG, e.toString());
			}
			
			break;
		default:
			Log.e(TAG,"Error: server returned - " + statusCode);
			break;
			
		}
		
		return data;
	}

	@Override
	protected void onPostExecute(String result) {
		Log.i(TAG, "< onPostExecute >");
		super.onPostExecute(result);
		if(st!=null){
		st.hideStatus();
		st.processJson(result);
		}
//		new AsyncHandleResponse().execute(result);
	}
	
	
	
	@Override
	protected void onCancelled() {
		Log.w(TAG, "< onCancelled >");
		super.onCancelled();
		Utils.showToast("The HTTP request has been cancelled");
	}

	public HttpResponse getResponseForRequest(HttpClient httpClient) throws ClientProtocolException, IOException {
	Log.i(TAG, "< getResponseForRequest >");

	HttpDelete httpDelete = null;
	HttpGet httpGet = null;
	HttpPost httpPost = null;
	HttpPut httpPut = null;
	String URL = sr.getPath();
	String method = sr.getMethod();

	Log.i(TAG, "Method: " + method);
	Log.i(TAG, "URL: " + URL);

	if (method.equals("DELETE")){
		httpDelete = new HttpDelete(URL);
//		httpDelete.setHeader("sessionId", deviceId);
		return httpClient.execute(httpDelete);
	}

	else if (method.equals("GET")){
		httpGet = new HttpGet(URL);
		httpGet.setHeader("sessionId", "dsda");
		return httpClient.execute(httpGet);
	}

	else if (method.equals("POST")) {
		httpPost = new HttpPost(URL);
		httpPost.setEntity(new StringEntity(sr.getBody()));
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Content-type", "application/json");
		httpPost.setHeader("charset", "UTF-8");
//		httpPost.setHeader("sessionId", deviceId);

		return httpClient.execute(httpPost);
	}

	else if (method.equals("PUT")) {
		httpPut = new HttpPut(sr.getPath());
		httpPut.setEntity(new StringEntity(sr.getBody()));
		httpPut.setHeader("Accept", "application/json");
		httpPut.setHeader("Content-type", "application/json");
		httpPut.setHeader("charset", "UTF-8");
//		httpPut.setHeader("sessionId", deviceId);

		return httpClient.execute(httpPut);
	}

	return null;
}
	
}
